<template>
    <!-- <h3>歌手信息管理</h3> -->
    <div class="page-toggle">
        <div @click="addSongFn" :class="['toggle-button', { active: num == 0 }]">发布歌曲</div>
        <span>|</span>
        <div @click="listSongFn" :class="['toggle-button', { active: num == 1 }]">歌曲列表</div>
    </div>
    <!-- 表单 -->
    <div class="song-form" v-if="num == 0">
        <!-- 歌曲信息 -->
        <div class="wrapper2">
            <div class="left">
                <div class="opt">
                    <el-input v-model="song.song_name" style="width: 360px; height: 44px; font-size: 16px"
                        placeholder="歌曲名称" />
                </div>
                <div class="opt">
                    <el-select v-model="song.category_name" placeholder="请选择歌曲分类">
                        <el-option v-for="item in categorys" :label="item.category_name" :value="item.category_name" />
                    </el-select>
                </div>
                <!-- 选择歌手 -->
                <div class="opt" style="width: 360px;">
                    <div>
                        <el-input v-model="singerInput" style="width: 360px; height: 44px; font-size: 16px"
                            placeholder="请输入歌手(或关键字)" />
                    </div>
                    <el-select v-model="selectedSingerValue" placeholder="请选择歌手">
                        <el-option v-for="item in singers" :label="item.singer_name" :value="item.singer_id" />
                    </el-select>
                </div>

                <!-- 选择专辑 -->
                <div class="opt" style="width: 360px;">
                    <div>
                        <el-input v-model="albumInput" style="width: 360px; height: 44px; font-size: 16px"
                            placeholder="请输入专辑(或关键字)" />
                    </div>
                    <el-select v-model="selectedAlbumValue" placeholder="请选择专辑">
                        <el-option v-for="item in albums" :label="item.album_name" :value="item.album_id" />
                    </el-select>
                </div>

                <div class="opt">
                    <span class="label">选择时间</span>
                    <div class="block">
                        <el-date-picker v-model="song.release_time" type="date" placeholder="请选择发布时间" size="default"
                            style="width: 360px; font-size: 16px" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                    </div>
                </div>

            </div>
            <div class="right">
                <div class="opt">
                    <span class="label">选择封面图片</span>
                    <!-- 上传文件组件 -->
                    <el-upload class="avatar-uploader avatar-uploader2" drag action="#" :on-change="chooseImageFn"
                        :auto-upload="false" :show-file-list="false">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar2" />
                        <el-icon v-else class="avatar-uploader-icon2">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <div v-if="imageUrl" style="width: 178px; margin-top: 5px">
                        <el-button @click="photoDeleteFn(imageUrl)" type="danger" plain>删除图片</el-button>
                    </div>
                </div>


                <div class="opt">
                    <span class="label">添加音频文件</span>
                    <!-- 上传文件组件 -->
                    <!--  -->
                    <audio v-if="audioUrl" :src="audioUrl" controls></audio>

                    <el-upload v-if="!audioUrl" class="avatar-upload" drag action="#" :on-change="chooseAudioFn"
                        :auto-upload="false" :show-file-list="false">
                        <el-icon class="avatar-uploader-icon2">
                            <UploadFilled />
                        </el-icon>
                    </el-upload>

                    <div v-if="audioUrl" style="width: 178px; margin-top: 5px">
                        <el-button @click="audioDeleteFn(audioUrl)" type="danger" plain>删除音频</el-button>
                    </div>

                </div>
            </div>
        </div>
        <!-- 输入歌词文本 -->
        <div class="wrapper3">
            <div class="opt">
                <span class="label">填写歌曲</span>
                <div class="lyric" contenteditable="true" @input="addLyricText"></div>
            </div>
        </div>

        <div class="opt">
            <el-button @click="addSongInfoFn" type="primary" size="large">发布歌曲</el-button>
        </div>

    </div>

    <!-- 表格 -->
    <div class="song-table" v-if="num == 1">
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="index" label="序号" width="90" align="center"/>
            <el-table-column prop="song_name" label="歌曲名称" width="180" align="center"/>
            <el-table-column prop="category_name" label="分类" width="100" align="center" />
            <el-table-column prop="singer_name" label="歌手" width="120" align="center" />
            <el-table-column prop="singer_id" label="歌手ID" width="80" align="center" />
            <el-table-column prop="album_id" label="专辑ID" width="80" align="center" />
            <el-table-column prop="release_time" label="发布时间" width="180" align="center" />
            <el-table-column label="封面图片" width="180" align="center">
                <template #default="scope">
                    <!-- scope.row.name -->
                    <img style="width: 60px;" v-if="scope.row.song_cover_url" :src="scope.row.song_cover_url" alt="">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="搜索" />
                </template>
                <template #default="scope">
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页器 -->
    <div class="page" v-if="num == 1">
        <!-- :page-count="page" -->
        <el-pagination :page-size="pageSize" :pager-count="pageSize" layout="prev, pager, next" :total="totalNum"
            @change="changePageFn" />
    </div>

</template>


<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { photoUpload, photoDelete, audioUpload, audioDelete, addSong, itemsSong, removeSong, searchAlbum, searchSinger, searchSong, listSongCategory } from '../../api/request'
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Action } from 'element-plus'
import api from '../../api/index'

const albumInput = ref('')
const selectedAlbumValue = ref('')
const singerInput = ref('')
const selectedSingerValue = ref('')
const imageUrl = ref('')
const audioUrl = ref('')
const pic = ref('')
const src = ref('')

// 控制发布歌曲和歌曲列表
const num = ref(1)

// 歌曲数量
let totalNum = ref(0)
let page = ref(1)
let pageSize = ref(9)
const search = ref('')

interface Singer {
    [key: string]: any
}
interface Alblum {
    [key: string]: any
}
interface Category {
    [key: string]: any
}
// 定歌手数组
const singers = ref<Singer>([])
const albums = ref<Alblum>([])
const categorys = ref<Category>([])

// 选择歌手信息
let d: any = null;
watch(singerInput, (value: string) => {
    if (d != null) clearTimeout(d)
    d = setTimeout(() => {
        // console.log(value);
        // if(value == "") return ;
        searchSinger({ keyword: value })
            .then(
                content => {
                    // console.log(content)
                    let { result, code } = content;
                    if (code == 200) {
                        singers.value = result;
                        if (result) {
                            selectedSingerValue.value = result[0].singer_name
                            song.singer_id = result[0].singer_id;
                            song.singer_name = result[0].singer_name;
                        }
                    }
                }
            )
            .catch(err => console.log(err))
    }, 300)
})

// watch(selectedAlbumValue,(value:string)=>{
//     singerInput.value = value
// },{immediate: true})

// 选择专辑信息
let d2: any = null;
watch(albumInput, (value: string) => {
    if (d2 != null) clearTimeout(d2)
    d2 = setTimeout(() => {
        // console.log(value);
        // if(value == "") return ;
        searchAlbum({ keyword: value })
            .then(
                content => {
                    // console.log(content)
                    let { result, code } = content;
                    if (code == 200) {
                        albums.value = result;
                        if (result) {
                            // 默认专辑名称
                            selectedAlbumValue.value = result[0].album_name
                            // 默认专辑id
                            song.album_id = result[0].album_id;
                        }
                    }
                }
            )
            .catch(err => console.log(err))
    }, 300)
})


watch(search, async (value: any) => {

    if (value == "") {
        getSongListFn();
    }
    else {
        // console.log(value);
        await searchSong({ keyword: value })
            .then(
                content => {
                    // console.log(content)
                    let { code, result, total } = content;
                    if (code == 200) {
                        // 整合后台数据
                        let arr = result.map((item: Item, index: number) => {
                            item.index = index + 1;
                            item.song_cover_url = api.url + item.song_cover_url
                            item.release_time = new Date(item.release_time).toLocaleDateString()
                            return item;
                        })
                        tableData.value = arr;
                        totalNum.value = total || 0;
                        // console.log({total})
                    }
                }
            )
    }
})

// 定义每一项数据的属性类型
// song_name, singer_id, album_id, lyrics, release_time, song_cover_url
type Item = {
    song_id: number
    index?: string | number,
    song_name: string
    album_id: string
    lyrics: string
    release_time: string
    song_cover_url: string
    singer_name: string
    category_name: string
}
// 定义表单信息对象
const song = reactive({
    song_name: "",
    singer_id: "",
    album_id: "",
    lyrics: "",
    release_time: "",
    singer_name: "",
    category_name: "",
})

// 表格数据
const tableData = ref<any>([])

// 切换选项
const addSongFn = () => num.value = 0;
const listSongFn = () => num.value = 1;

// 选择图片
const chooseImageFn = async (file: any) => {
    if (file) {
        // 创建表单实例
        let fd = new FormData()
        fd.append('photo', file.raw) // 把图片信息传递给服务器 ，服务器存储好图片，再返回一个图片路径
        // 调用上传图片的方法
        await photoUpload(fd)
            .then(
                content => {
                    console.log("图片路径:", content)
                    let { code, picUrl } = content;
                    if (code == 200) {
                        // 赋值（响应式）
                        imageUrl.value = api.url + picUrl;
                        pic.value = picUrl;
                    }
                    else {
                        ElMessage.error(content.msg);
                    }
                }
            )
    }

}

// 删除图片
const photoDeleteFn = async (picUrl: string) => {
    await photoDelete({ picUrl })
        .then(
            content => {
                console.log(content);
                let { code } = content;
                if (code == 200) {
                    // 重置图片路径
                    imageUrl.value = "";
                }
            }
        )
        .catch(err => console.log(err))
}

// 选择音频
const chooseAudioFn = async (file: any) => {
    if (file) {
        // 创建表单实例
        let fd = new FormData()
        fd.append('audio', file.raw) // 把图片信息传递给服务器 ，服务器存储好图片，再返回一个图片路径
        // 调用上传图片的方法
        await audioUpload(fd)
            .then(
                content => {
                    console.log("音频路径:", content)
                    let { code } = content;
                    if (code == 200) {
                        // 赋值（响应式）
                        audioUrl.value = api.url + content.audioUrl;
                        src.value = content.audioUrl;
                    }
                    else {
                        ElMessage.error(content.msg);
                    }
                }
            )
    }

}
// 删除音频
const audioDeleteFn = async (src: string) => {
    await audioDelete({ audioUrl: src })
        .then(
            content => {
                console.log(content);
                let { code } = content;
                if (code == 200) {
                    // 重置图片路径
                    audioUrl.value = "";
                }
            }
        )
        .catch(err => console.log(err))
}

// 添加歌曲
const addSongInfoFn = async () => {
    //  song_name, singer_id, album_id, lyrics, release_time, song_cover_url, src (音频地址)
    let { song_name, singer_id, album_id, lyrics, release_time, singer_name, category_name } = song

    // 歌曲封面
    let song_cover_url = pic.value

    if (song_name == '' || singer_id == '' || album_id == '' || lyrics == '' || release_time == '') {
        ElMessage.error("缺少参数，请检查再提交");
        return false;
    }

    // console.log({song_name, singer_id, album_id, lyrics, release_time, song_cover_url, src: src.value, singer_name, category_name })

    await addSong({ song_name, singer_id, album_id, lyrics, release_time, song_cover_url, src: src.value, singer_name, category_name })
        .then(
            content => {
                console.log(content)
                let { code, msg } = content;
                // 添加分类名称成功
                if (code == 200) {
                    ElMessage.success(msg);
                    // 重置表单
                    song.song_name = ""
                    song.singer_id = ""
                    song.lyrics = ""
                    song.album_id = ""
                    song.release_time = ""
                    pic.value = ""
                    imageUrl.value = ""
                    selectedSingerValue.value = ""
                    selectedAlbumValue.value = ""
                    src.value = ""
                    audioUrl.value = ""
                    albumInput.value = ""
                    singerInput.value = ""
                    albums.value = []
                    singers.value = []
                    // 切换
                    num.value = 1;
                    // 重新获取列表
                    getSongListFn();
                }
                else {
                    ElMessage.error(msg)
                }
            }
        )
}

// 点击删除歌曲
const handleDelete = (index: number, row: any) => {
    // console.log(index, row)
    // 获取当前点击的选项
    let { song_id, song_cover_url, song_name, src } = row;
    ElMessageBox.confirm(
        `是否删除这个“${song_name}歌曲?`,
        'Confirm',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(async () => {
            // console.log("点击确定")
            // 删除歌手
            await removeSong({ song_id })
                .then(
                    content => {
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )
            // 删除分类对应的图片
            await photoDelete({ picUrl: song_cover_url })
                .then(
                    content => {
                        // console.log(content);
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )

            // 删除分类对应的音频
            await audioDelete({ audioUrl: src })
                .then(
                    content => {
                        // console.log(content);
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        }
                    }
                )
            // 删除程序中数组对应的数据
            tableData.value.splice(index, 1);
        })
        .catch((action: Action) => {
            // console.log("点击取消")
        })

}
// 获取歌曲列表
const getSongListFn = async (page = 1, pageSize = 10) => {
    await itemsSong({ page, pageSize })
        .then(
            content => {
                // console.log(content)
                let { code, result,  total} = content;
                if (code == 200) {
                    // 整合后台数据
                    let arr = result.map((item: Item, index: number) => {
                        item.index = index + 1;
                        item.song_cover_url = api.url + item.song_cover_url
                        item.release_time = new Date(item.release_time).toLocaleDateString()
                        return item;
                    })
                    tableData.value = arr;
                    totalNum.value = total || 0;
                }
            }
        )
}

// 获取歌曲对应歌词文本
let d3: any = null
const addLyricText = function (event: any) {
    if (d3 != null) clearTimeout(d3);
    d3 = setTimeout(() => {
        // console.log(event.target.innerText)
        if (event.target.innerText) {
            song.lyrics = event.target.innerText
        }
    }, 300)
}

// 点击分页时执行的函数
const changePageFn = (num: number) => {
    // console.log(value)
    page.value = num;
    getSongListFn(page.value, pageSize.value);
}

// 获取歌曲分类
const listCategoryFn = async () => {
   await listSongCategory().then(
    content => {
        let { result, code } = content;
        if (code == 200) {
            categorys.value = result;
        }
    }
)
}
// 初始化
getSongListFn();
listCategoryFn();

</script>

<style lang="scss">
@import '../../common/scss/common.scss';

.song-form .opt,
.song-table {
    margin-top: 15px;
}

.opt .label {
    color: #666;
    padding: 5px;
    margin-bottom: 5px;
    display: block;
}

.el-upload-dragger,
.avatar-uploader-icon2,
.avatar-uploader2,
.avatar2 {
    width: 128px;
    height: 128px;
    display: block;
    padding: 0 !important;
}

.avatar-uploader-icon2 {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    text-align: center;
    padding: 0 !important;
    line-height: 128px;
}

// .avatar-upload {
//     .el-upload-dragger {

//     }
// }

.wrapper2 {
    width: 100%;
    display: flex;
    background-color: #fff;
    padding: 20px;
    margin-top: 15px;
}

.wrapper2 .left {
    margin-right: 20px;
}

.wrapper3 {
    background-color: #fff;
    padding: 0px 20px 20px 20px;
}

.wrapper3 .lyric {
    width: 100%;
    height: 600px;
    border: 1px solid #ccc;
    padding: 15px;
    outline-color: deepskyblue;
    overflow: scroll;
}

::-webkit-scrollbar {
    display: none;
}
</style>